package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.service.CategoryService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 分类管理
 * @author GRS
 * @since 2024/4/19 下午5:02
 */
@RestController
@RequestMapping("/category")
public class CategoryController
{
    @Resource
    private CategoryService categoryService;

    /**
     * 新增分类
     */
    @PostMapping
    public R<String> save(@RequestBody Category category)
    {
        categoryService.save(category);
        return R.success("分类添加成功");
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    public R<IPage<Category>> page(Long page, Long pageSize, String name)
    {
        Page<Category> categoryPage = new Page<>(page, pageSize);

        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name != null, Category::getName, name);
        wrapper.orderByDesc(Category::getSort);

        IPage<Category> pageModel = categoryService.page(categoryPage, wrapper);

        return R.success(pageModel);
    }

    /**
     * 根据ID删除分类
     */
    @DeleteMapping("/{id}")
    public R<String> delete(@PathVariable("id") Long id)
    {
        categoryService.removeById(id);

        return R.success("分类信息删除成功");
    }

    /**
     * 根据ID修改分类信息
     */
    @PutMapping
    public R<String> update(@RequestBody Category category)
    {
        categoryService.updateById(category);
        return R.success("修改分类信息成功");
    }

    /**
     * 根据条件查询分类数据
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category)
    {
        // 条件构造器
        LambdaQueryWrapper<Category> wrapper = new LambdaQueryWrapper<>();

        // 添加条件
        wrapper.eq(category.getType() != null, Category::getType, category.getType())
            // 添加排序条件
            .orderByAsc(Category::getSort)
            .orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(wrapper);
        return R.success(list);
    }
}